package com.example.hrsystem.data.repository;

import android.app.Application;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import com.example.hrsystem.data.model.User;
import com.example.hrsystem.data.source.AppDatabase;
import com.example.hrsystem.data.source.UserDao;

import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 用户数据仓库类
 * 封装对用户数据的访问逻辑，提供统一的接口给ViewModel使用
 */
public class UserRepository {

    private UserDao userDao;
    private LiveData<List<User>> allUsers;

    /**
     * 构造方法
     */
    public UserRepository(Application application) {
        AppDatabase database = AppDatabase.getDatabase(application);
        userDao = database.userDao();
        allUsers = userDao.getAllUsers();
    }

    /**
     * 获取所有用户
     */
    public LiveData<List<User>> getAllUsers() {
        return allUsers;
    }

    /**
     * 根据用户ID获取用户
     */
    public LiveData<User> getUserById(int userId) {
        return userDao.getUserById(userId);
    }

    /**
     * 根据员工工号获取用户
     */
    public LiveData<User> getUserByEmployeeId(String employeeId) {
        return userDao.getUserByEmployeeId(employeeId);
    }

    /**
     * 根据部门获取用户
     */
    public LiveData<List<User>> getUsersByDepartment(String department) {
        return userDao.getUsersByDepartment(department);
    }

    /**
     * 获取在职员工
     */
    public LiveData<List<User>> getActiveUsers() {
        return userDao.getActiveUsers();
    }

    /**
     * 根据用户类型获取用户
     */
    public LiveData<List<User>> getUsersByUserType(String userType) {
        return userDao.getUsersByUserType(userType);
    }

    /**
     * 插入用户
     */
    public void insert(User user) {
        try {
            if (user == null || userDao == null) {
                return;
            }
            new InsertUserAsyncTask(userDao).execute(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新用户
     */
    public void update(User user) {
        new UpdateUserAsyncTask(userDao).execute(user);
    }

    /**
     * 删除所有用户
     */
    public void deleteAll() {
        new DeleteAllUsersAsyncTask(userDao).execute();
    }

    /**
     * 同步检查用户是否存在
     */
    public boolean isUserExistsSync(int userId) {
        try {
            return new IsUserExistsSyncTask(userDao).execute(userId).get() > 0;
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 检查手机号是否已存在（回调版本）
     */
    public interface PhoneNumberExistsCallback {
        void onResult(boolean exists);
    }

    public void isPhoneNumberExists(String phoneNumber, PhoneNumberExistsCallback callback) {
        if (callback == null) {
            return;
        }
        
        try {
            new IsPhoneNumberExistsAsyncTask(userDao, callback).execute(phoneNumber);
        } catch (Exception e) {
            e.printStackTrace();
            // 确保回调总是被调用
            try {
                callback.onResult(false);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 根据手机号和密码验证用户登录（回调版本）
     */
    public interface UserAuthenticateCallback {
        void onResult(User user);
    }

    public void authenticateUser(String phoneNumber, String password, UserAuthenticateCallback callback) {
        if (callback == null) {
            return;
        }
        
        try {
            new AuthenticateUserAsyncTask(userDao, callback).execute(phoneNumber, password);
        } catch (Exception e) {
            e.printStackTrace();
            // 确保回调总是被调用
            try {
                callback.onResult(null);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    // 原始同步版本保留，供需要的地方使用
    public boolean isPhoneNumberExistsSync(String phoneNumber) {
        try {
            return new IsPhoneNumberExistsSyncTask(userDao).execute(phoneNumber).get() > 0;
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return false;
        }
    }

    public User authenticateUserSync(String phoneNumber, String password) {
        try {
            return new AuthenticateUserSyncTask(userDao).execute(phoneNumber, password).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 同步获取用户信息
     */
    public User getUserByIdSync(int userId) {
        try {
            return new GetUserByIdSyncTask(userDao).execute(userId).get();
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }

    // AsyncTask类用于在后台线程执行数据库操作
    private static class InsertUserAsyncTask extends AsyncTask<User, Void, Void> {
        private UserDao userDao;

        private InsertUserAsyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected Void doInBackground(User... users) {
            try {
                if (userDao != null && users != null && users.length > 0 && users[0] != null) {
                    userDao.insert(users[0]);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    private static class UpdateUserAsyncTask extends AsyncTask<User, Void, Void> {
        private UserDao userDao;

        private UpdateUserAsyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected Void doInBackground(User... users) {
            userDao.update(users[0]);
            return null;
        }
    }

    private static class DeleteAllUsersAsyncTask extends AsyncTask<Void, Void, Void> {
        private UserDao userDao;

        private DeleteAllUsersAsyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            userDao.deleteAll();
            return null;
        }
    }

    private static class IsUserExistsSyncTask extends AsyncTask<Integer, Void, Integer> {
        private UserDao userDao;

        private IsUserExistsSyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected Integer doInBackground(Integer... userIds) {
            return userDao.isUserExists(userIds[0]);
        }
    }

    private static class IsPhoneNumberExistsSyncTask extends AsyncTask<String, Void, Integer> {
        private UserDao userDao;

        private IsPhoneNumberExistsSyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected Integer doInBackground(String... phoneNumbers) {
            return userDao.isPhoneNumberExists(phoneNumbers[0]);
        }
    }

    private static class IsPhoneNumberExistsAsyncTask extends AsyncTask<String, Void, Integer> {
        private UserDao userDao;
        private PhoneNumberExistsCallback callback;

        private IsPhoneNumberExistsAsyncTask(UserDao userDao, PhoneNumberExistsCallback callback) {
            this.userDao = userDao;
            this.callback = callback;
        }

        @Override
        protected Integer doInBackground(String... phoneNumbers) {
            try {
                return userDao.isPhoneNumberExists(phoneNumbers[0]);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }

        @Override
        protected void onPostExecute(Integer count) {
            if (callback != null) {
                callback.onResult(count > 0);
            }
        }
    }

    private static class AuthenticateUserSyncTask extends AsyncTask<String, Void, User> {
        private UserDao userDao;

        private AuthenticateUserSyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected User doInBackground(String... params) {
            String phoneNumber = params[0];
            String password = params[1];
            return userDao.getUserByPhoneAndPassword(phoneNumber, password);
        }
    }

    private static class AuthenticateUserAsyncTask extends AsyncTask<String, Void, User> {
        private UserDao userDao;
        private UserAuthenticateCallback callback;

        private AuthenticateUserAsyncTask(UserDao userDao, UserAuthenticateCallback callback) {
            this.userDao = userDao;
            this.callback = callback;
        }

        @Override
        protected User doInBackground(String... params) {
            try {
                String phoneNumber = params[0];
                String password = params[1];
                return userDao.getUserByPhoneAndPassword(phoneNumber, password);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(User user) {
            if (callback != null) {
                callback.onResult(user);
            }
        }
    }

    private static class GetUserByIdSyncTask extends AsyncTask<Integer, Void, User> {
        private UserDao userDao;

        private GetUserByIdSyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected User doInBackground(Integer... userIds) {
            try {
                if (userDao != null && userIds != null && userIds.length > 0) {
                    return userDao.getUserByIdSync(userIds[0]);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}